import React, { Component } from 'react';
import {
	StyleSheet, Text, View, Image, TouchableOpacity, Dimensions, ActivityIndicator, Modal
} from "react-native";
import { NavigationEvents } from 'react-navigation';
import navigationSeevice from '../../../../components/navigation/navigationSeevice';
import { GLOBAL } from '../../../../config/global';
import StorageHelper from '../../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../../config/storage';
import { API, API_GENERATE } from '../../../../config/api';
import HTTP from '../../../../utils/http';
import { style } from '../../../../theme/style';
import { Common } from '../../../../component/common/Common';
import { headTab } from '../_common/data';
import { EnBaseInfoComponent } from './base-info/itemframe';
import { EnCreditComponent } from './credit/itemframe';
import { TrTeComponent } from './transaction-records/itemframe';
import { MaReComponent } from './maintenance-record/itemframe';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import ModalPicsComponent from './_components/ModalPicsComponent';
import { NewAccount } from '../../../../components/common/newAccount';
import { SlideSelect } from '../../../../components/common/slideSelect';
import ScrollableTabView, { DefaultTabBar, ScrollableTabBar } from 'react-native-scrollable-tab-view';
import Utils from "../../../../utils/utils";
const scale = GLOBAL.SCALE;

const modalPicDelCfg = {
	visible: false,
	urls: [],
	picPress: () => { },
}

export class EnterpriseDetailsPage extends Component {
	static navigationOptions = ({ navigation }) => {
		return {
			headerTitle: '我的客户详情',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigationSeevice.goBack() }} color='#fff' />,
			headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../../../imgs/goBackEmpty.png')} />),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center',
			}
		}
	};

	constructor(props) {
		super(props);
		let { tabIndex, companyId, currentCreditType, creditApplyStatus, choice, companyIndex } = this.props.navigation.state.params || {};
		console.log('我的客户详情-choice', choice, companyIndex)
		this.currentCreditType = currentCreditType || null;//其他页面跳转至授信页面的类型
		this.creditApplyStatus = creditApplyStatus || null;//其他页面跳转至授信页面的类型
		this.tabData = headTab || [];
		this.companyIndex = companyIndex || 0;
		this.params = {
			isPage: 0,
			companyId,
			pageNo: 1,
		};

		this.state = {
			pageStatus: 'loading',
			tabIndex: 0,
			previewModalVisible: false,
			loading: false,
			alertShow: false,
			options: [],
			choice: choice || {}
		}
	}

	async	componentWillMount() {
		await this._init();
		let { tabIndex } = this.props.navigation.state.params || {};
		/* 临时处理 */
		setTimeout(() => {
			this.setState({
				tabIndex: tabIndex || 0
			})
		}, 2000);
	}

	//初始调用
	_init = async () => {
		this.setState({ pageStatus: 'loading' });
		let customerInfo = await this.getDetail(this.params);
		if (customerInfo) {
			this.setState({ pageStatus: 'data' });
			// this.checkIfEdit(customerInfo);
			this.getBizCompanyGoods(customerInfo);
		} else {
			this.setState({ pageStatus: 'error' });
		}
	}
	resetInfo = (data) => {
		if (data) {
			this.setState({
				customerInfo: data
			})
		}
	}
	//检查是否可编辑
	async checkIfEdit(customerInfo) {
		const { status } = this.props.navigation.state.params || {};
		const { staffCompanyList, corpInfoTOs } = customerInfo;
		const userInfoJson = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
		const userInfo = JSON.parse(userInfoJson);

		//过滤业务经办人中是否含有当前登录人，如果有，则可以进行编辑等操作
		const staff = staffCompanyList.length ? staffCompanyList.filter((item, index) => {
			return item.staffId === userInfo.userId;
		}) : [];
		this.setState({
			customerInfo,
			ifEdit: staff.length && status,
			options: corpInfoTOs || [],
			choice: this.state.choice.corpId ? this.state.choice : (corpInfoTOs && corpInfoTOs.length ? corpInfoTOs[0] : '')
		})
	}

	//业务员经营品类列表
	async	getBizCompanyGoods(customerInfo) {
		const { companyInfoVO } = customerInfo || {};
		const reponse = await HTTP.POST(API_GENERATE(API.GET_BIZ_COMPANY_GOODS), { companyId: companyInfoVO.companyId, corpId: this.state.choice.corpId });
		customerInfo.bizCompanyGoodsList = reponse;
		// this.setState({ customerInfo });
		this.checkIfEdit(customerInfo);
	}
	//提前获取资质图片
	getImgView(item) {
		const { qualificationAddress } = item || {};
		if (!qualificationAddress) return;
		if (this.request) return;
		this.request = true;
		this.setState({ loading: true })
		const qualificationArr = qualificationAddress.split(',');
		qualificationArr.map(async (fileId, index) => {
			await this.loadedImgs(fileId, qualificationArr.length, index);
		})
	}

	async	loadedImgs(fileId, length, index) {
		const response = await HTTP.GET(API_GENERATE(API.GET_IMG_VIEW), { fileId });
		if (response && response.image && response.image.length) {
			modalPicDelCfg.visible = true;
			modalPicDelCfg.urls.push({
				url: response.image,
				width: Dimensions.get('window').width
			});
			modalPicDelCfg.picPress = () => {
				modalPicDelCfg.visible = false;
				modalPicDelCfg.urls = [];
				this.setState({
					previewModalVisible: false,
				});
			}

			if (modalPicDelCfg.urls.length == length) {
				this.request = false;
				this.setState({
					loading: false,
					previewModalVisible: true
				});
			}
		} else {
			this.request = false;
			modalPicDelCfg.visible = false;
			modalPicDelCfg.urls = [];
			this.setState({ loading: false })
		}
	}

	//正式表详情（我的客户）
	async getDetail(params) {
		const { status, id } = this.props.navigation.state.params || {};
		let responseData;
		params.corpId = this.state.choice.corpId;
		if (status) {
			//正式表正的客户详情
			responseData = await HTTP.POST(API_GENERATE(API.GET_CUSTOMER_DETAIL), params);
		} else {
			//审核中的详情
			params.id = id;
			responseData = await HTTP.POST(API_GENERATE(API.GET_CUSTOMER_APPLY_DETAIL), params);
		}
		return responseData;
	}

	// tab切换
	_tabFn = tabIndex => { this.setState({ tabIndex }) }

	//跳转外部连接
	_goOrderListPage = (url, params = {}) => {
		this.setState({ tabIndex: 0 });
		this.props.navigation.navigate(url, params);
	}



	_renderTitleView() {
		let { ifEdit, choice, options } = this.state;
		if (options.length > 1) {
			<NewAccount fn={(val) => { this.setState({ alertShow: val }) }} choice={choice.corpName || ''} />
		} else {
			return null
		}
	}

	render() {
		let { tabIndex, customerInfo, ifEdit, pageStatus, loading, alertShow, choice, options } = this.state;
		const { status, id } = this.props.navigation.state.params || {};
		const titleView = this._renderTitleView();
		return (
			<View style={styles.container}>
				{titleView}
				<View style={styles.headBox}>
					{/* {status ?
						<View style={styles.tabBox}>
							<ScrollableTabView
								renderTabBar={() => <ScrollableTabBar tabStyle={{ paddingLeft: 0, paddingRight: 0, width: 83 * scale }} style={{ borderBottomWidth: 0 }} />}
								//page={tabIndex}
								locked={true}
								initialPage={tabIndex}
								scrollWithoutAnimation={true}
								onChangeTab={(obj) => {
									console.log("点击才走")
									this._tabFn(obj.i);
								}}
								tabBarUnderlineStyle={{ backgroundColor: style.color.white }}
								tabBarActiveTextColor='#FFF'
								tabBarInactiveTextColor='#FFF'
								tabBarUnderlineStyle={styles.tabBarUnderline}
							>
								{this.tabData && this.tabData.map((item, index) => {
									return (
										<Text key={index} style={styles.tabText} tabLabel={item.title} />
									)
								})}
							</ScrollableTabView>
						</View> : null} */}
					<View style={styles.tabBox}>
						{
							status ? (this.tabData && this.tabData.map((item, index) => {
								return (
									<TouchableOpacity key={index} style={[styles.tabTextBox, tabIndex == index ? styles.tabTextBoxActive : null]} onPress={() => { this._tabFn(index) }}>
										<Text style={styles.tabText}>{item.title}</Text>
									</TouchableOpacity>
								)
							})) : null
						}
					</View>
				</View>
				{
					pageStatus == 'data' ?
						<View style={[styles.iframe, { marginTop: status ? -20 * scale : -50 * scale }]}>
							{tabIndex == 0 && customerInfo ? <EnBaseInfoComponent choice={choice} data={customerInfo} ifEdit={ifEdit} status={status} id={id} checkQualificationImage={(item) => this.getImgView(item)} review={(data) => this.resetInfo(data)} /> : null}
							{tabIndex == 1 && customerInfo && status ? <EnCreditComponent choice={choice} data={customerInfo} ifEdit={ifEdit} currentCreditType={this.currentCreditType} creditApplyStatus={this.creditApplyStatus} /> : null}
							{tabIndex == 2 && customerInfo && status ? this._goOrderListPage('clientFundsDetail', { companyId: customerInfo.companyInfoVO.companyId, companyName: customerInfo.companyInfoVO.companyName, companyIndex: this.companyIndex }) : null}
							{tabIndex == 3 && customerInfo && status ? this._goOrderListPage('OrderListPage', {
								companyId: customerInfo.companyInfoVO.companyId,
								companyName: customerInfo.companyInfoVO.companyName,
								choice
							}) : null}
							{tabIndex == 4 && customerInfo && status ? <MaReComponent choice={choice} ortherData={customerInfo} /> : null}
						</View>
						: <PageStatusIndex status={pageStatus} emptyText={'暂无记录'} onErrorPress={this._init} />}

				{/**预览图片预加载 */}
				{
					loading ?
						<View style={styles.loadingView}>
							<View style={styles.loadedCell}>
								<ActivityIndicator
									animating={true}
									color={'#fff'}
									size="small"
								/>
							</View>
						</View>
						: <ModalPicsComponent {...modalPicDelCfg} />
				}
				<SlideSelect alertShow={alertShow} options={options}
					select={(val) => {
						this.setState({ choice: val || options[0], alertShow: false }, () => {
							this._init();
						})
					}}
					unselect={() => {
						this.setState({ alertShow: false })
					}} />
			</View>
		)
	}
}


const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray
	},
	headerView: {
		backgroundColor: style.color.themeColor,
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		paddingTop: 28 * scale
	},
	headerText: {
		flex: 1,
		textAlign: 'center',
		color: '#fff',
		fontSize: 20 * scale,
		fontWeight: 'bold'
	},
	headBox: {
		width: '100%',
		backgroundColor: style.color.themeColor,
	},
	tabBarUnderline: {
		backgroundColor: '#fff',
		height: 2 * scale,
	},
	tabBox: {
		flexDirection: 'row',
		justifyContent: 'space-around',
		paddingBottom: 40 * scale,
		paddingTop: 14 * scale
	},
	tabText: {
		color: '#fff',
		fontSize: 13 * scale,
		lineHeight: 30 * scale,
	},
	tabTextBox: {
		paddingLeft: 2 * scale,
		paddingRight: 2 * scale,
	},
	tabTextBoxActive: {
		borderBottomWidth: 2 * scale,
		borderStyle: 'solid',
		borderBottomColor: style.color.white,
	},
	iframe: {
		flex: 1,
		marginTop: -20 * scale
	},
	loadedCell: {
		width: 75 * scale,
		height: 75 * scale,
		backgroundColor: 'rgba(0, 0, 0, .5)',
		borderRadius: 7,
		justifyContent: 'center',
		alignItems: 'center',
		marginLeft: 150 * scale,
		marginTop: (Dimensions.get('window').height - 75) / 2,
	},
	loadingView: {
		width: 375 * scale,
		height: Dimensions.get('window').height,
		backgroundColor: 'rgba(0, 0, 0, 0.1)',
		position: 'absolute',
		top: 0
	}
})